package com.yiquan.user.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.yiquan.user.pojo.ApplyUpdateUserDTO;
import com.yiquan.user.pojo.UserActivity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.yiquan.user.pojo.User;
import com.yiquan.user.service.UserService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.web.multipart.MultipartFile;

/**
 * 控制器层
 *
 * @author Administrator
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(true, StatusCode.OK, "查询成功", userService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable Long id) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findById(id));
    }

    /**
     * 根据用户id查找用户
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "getUserByUserId", method = RequestMethod.GET)
    public Result findByUserId(@RequestParam Long userId) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findByUserId(userId));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<User> pageList = userService.findSearch(searchMap, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<User>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findSearch(searchMap));
    }

    /**
     * 增加
     *
     * @param user
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody User user) {
        userService.add(user);
        return new Result(true, StatusCode.OK, "增加成功");
    }

    /**
     * 修改
     *
     * @param user
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result updateUserById(@RequestBody User user, @PathVariable Long id) {
        userService.updateUserById(user, id);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /**
     * 根据id修改用户信息
     *
     * @param user
     * @param userId
     * @return
     */
    @PutMapping("/updateUserByUserId")
    public Result updateUserByUserId(@RequestBody User user, @RequestParam Long userId) {
        userService.updateUserByUserId(user, userId);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable Long id) {
        userService.deleteById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /**
     * 根据userId删除用户
     *
     * @param userId
     * @return
     */
    @DeleteMapping("/deleteByUserId")
    public Result deleteByUserId(@RequestParam Long userId) {
        userService.deleteByUserId(userId);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    @PostMapping("/uploadAvatar")
    public Result uploadAvatar(@RequestParam MultipartFile file, @RequestParam Long userId) {
        boolean success = userService.uploadAvatar(file, userId);
        if (success) {
            return new Result(true, StatusCode.OK, "图片上传成功");
        }
        return new Result(false, StatusCode.ERROR, "图片上传失败");
    }

    @PostMapping("/uploadBackground")
    public Result uploadBackground(@RequestParam MultipartFile file, @RequestParam Long userId) {
        String backgroundUrl = userService.uploadBackground(file, userId);
        if (!StringUtils.isEmpty(backgroundUrl)) {
            log.info("上传成功");
            return new Result(backgroundUrl);
        }
        return new Result(false, StatusCode.ERROR, "图片上传失败");
    }


    /**
     * 关注用户
     *
     * @param userId
     * @param followUserId
     * @return
     */
    @PostMapping("/followUser")
    public Result followUser(@RequestParam("userId") String userId, @RequestParam("followUserId") String followUserId) {
        boolean success = userService.followUser(Long.valueOf(String.valueOf(userId)), Long.valueOf(String.valueOf(followUserId)));
        if (success) {
            return new Result(true, StatusCode.OK, "操作成功");
        }
        return new Result(false, StatusCode.ERROR, "操作失败");
    }

    /**
     * 查询是否关注该用户
     *
     * @param userId
     * @param theUserId
     * @return
     */
    @GetMapping("/isFollow")
    public Result isFollowTheUserByUserId(@RequestParam("userId") Long userId, @RequestParam Long theUserId) {
        boolean isFollow = userService.isFollowTheUserByUserId(userId, theUserId);
        return new Result(true, StatusCode.OK, "操作成功", isFollow);

    }


    @PostMapping("/backend/search/{page}/{size}")
    public Result backendSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<User> search = userService.findSearch(searchMap, page, size);
        return new Result(new PageResult<User>(search.getTotalElements(), search.getContent()));
    }

    @GetMapping("/backend/synchronizeUserDate")
    public Result synchronizeUserData() {
        userService.synchronizeUserData();
        return new Result(StatusCode.REQUEST_SUCCESS);
    }

    @GetMapping("/updateUserWorkNums")
    public Result updateUserWorkNums(@RequestParam Long userId, @RequestParam Integer num) {
        userService.updateUserWorkNums(userId, num);
        return new Result(StatusCode.REQUEST_SUCCESS);
    }

    @GetMapping("/getUserActivity/{page}/{size}")
    public Result getUserActivity(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @RequestParam Long userId, @RequestParam Integer status) {
        PageResult<User> userActivity = userService.getUserActivity(page, size, userId, status);
        return new Result(userActivity);
    }


    @GetMapping("/getUserActivity")
    public Result getUserActivityAll(@RequestParam Long userId, @RequestParam Integer status) {
        List<Long> userActivity = userService.getUserActivityUserIdAll(userId, status);
        return new Result(userActivity);
    }

    @GetMapping("/getFriendListUserId")
    public Result getFriendListUserId(@RequestParam Long userId, @RequestParam Integer status) {
        List<Long> userActivity = userService.getFriendListUserId(userId, status);
        return new Result(userActivity);
    }

    @GetMapping("/updateUserActivity")
    public Result getUserActivity(@RequestParam Long userId, @RequestParam Integer status) {
        userService.updateVideoActivityStatus(userId, status);
        return new Result(StatusCode.OK);
    }

    /**
     * 申请更改账号类型 （认证为老师）
     *
     * @return
     */
    @PostMapping("/applyUpdateUserType")
    public Result applyUpdateUserType(@RequestBody ApplyUpdateUserDTO applyUpdateUserDTO) {
        userService.applyUpdateUserType(applyUpdateUserDTO);
        return new Result(StatusCode.OK);
    }

    /**
     * 上传认证资料
     *
     * @param file
     * @param userId
     * @return
     */
    @PostMapping("/uploadIdentify")
    public Result uploadIdentify(@RequestParam MultipartFile file, @RequestParam Long userId) {
        String identifyUrl = userService.uploadIdentify(file, userId);
        if (!StringUtils.isEmpty(identifyUrl)) {
            log.info("上传成功");
            return new Result(identifyUrl);
        }
        return new Result(false, StatusCode.ERROR, "图片上传失败");
    }

    @PutMapping("/identify")
    public Result agreeIdentify(@RequestParam Integer id, @RequestParam Boolean agree) {
        if (agree) {
            userService.agreeIdentify(id);
        } else {
            userService.disagreeIdentify(id);
        }
        return new Result(StatusCode.OK);
    }


    @PostMapping("/getIedentifyList/{page}/{size}")
    public Result getIdentifyList(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @RequestBody Map map) {
        Page<ApplyUpdateUserDTO> applyUpdateUserDTOS = userService.listIdentify(page, size, map);
        return new Result(new PageResult<>(applyUpdateUserDTOS.getTotalElements(), applyUpdateUserDTOS.getContent()));
    }

    @PutMapping("/updateUserStatusByUserId")
    public Result updateUserStatusByUserId(@RequestParam Long userId) {
        userService.updateUserStatusByUserId(userId);
        return new Result(StatusCode.OK);
    }

    @DeleteMapping("/batchDelete")
    public Result batchDelete(@RequestBody List<Long> userIdList) {
//        List<Long> userIds = new ArrayList<>();
//        userIdList.forEach(aLong -> userIds.add(Long.parseLong(aLong)));
        userService.batchDelete(userIdList);
        return new Result(StatusCode.OK);
    }

    @PostMapping("/getFriendList")
    public Result getFriendList(@RequestParam Long userId) {
        log.info("查询userId:{} 的好友列表",userId);
        return new Result(userService.getFriendList(userId, 0));
    }

    /**
     * 增加用户行为 关注 点赞 评论 @
     * @param userActivity
     * @return
     */
    @PostMapping("addUserActivity")
    public Result addUserActivity(@RequestBody UserActivity userActivity) {
        userService.addUserActivity(userActivity);
        return new Result(StatusCode.OK);
    }

    /**
     * 获取点赞行为 包括点赞视频 点赞评论
     * @param userId
     * @param page
     * @param size
     * @return
     */
    @GetMapping("getThumbActivity/{page}/{size}")
    public Result getThumbActivity(@RequestParam Long userId, @PathVariable Integer page, @PathVariable Integer size) {
        Page<UserActivity> thumbActivity = userService.getThumbActivity(page, size, userId);
        return new Result(new PageResult<UserActivity>(thumbActivity.getTotalElements(),thumbActivity.getContent()));
    }

    /**
     * 获取评论行为 包括评论视频 评论评论
     * @param userId
     * @param page
     * @param size
     * @return
     */
    @GetMapping("getCommentActivity/{page}/{size}")
    public Result getCommentActivity(@RequestParam Long userId, @PathVariable Integer page, @PathVariable Integer size) {
        Page<UserActivity> commentActivity = userService.getCommentActivity(page, size, userId);
        return new Result(new PageResult<UserActivity>(commentActivity.getTotalElements(), commentActivity.getContent()));
    }

    /**
     * 获取艾特行为
     * @param userId
     * @param page
     * @param size
     * @return
     */
    @GetMapping("getAiteActivity/{page}/{size}")
    public Result getAiteActivity(@RequestParam Long userId, @PathVariable Integer page, @PathVariable Integer size) {
        Page<UserActivity> aiteActivity = userService.getAiteActivity(page, size, userId);
        return new Result(new PageResult<UserActivity>(aiteActivity.getTotalElements(), aiteActivity.getContent()));
    }

    @PostMapping("updatePassword")
    public Result modifyPassword(@RequestParam Long userId,@RequestParam String oldPassword,@RequestParam String newPassword){
        boolean flag = userService.updatePassword(userId, oldPassword, newPassword);
        if (!flag){
            return new Result(StatusCode.ERROR);
        }
        return new Result(StatusCode.OK);
    }


}
